<?php

namespace App\Http\Controllers\Show;

use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class HotController extends ShowMasterController
{
    protected $pageSize = 20;
    protected $filter = true; //如果为true则用近30天方式进行获取数据，如果为false则加载最近100条数据

    public function index()
    {
        $navVisible = parent::getNavInfo();
        $starTime = Carbon::now()->subDays(30);
        $count = DB::table('goods_v')->where('status', '=', 1)
            ->whereDate('updated_at', '>', $starTime)
            ->count('*');

        if ($count < $this->pageSize * 2) {
            $this->filter = false;
            $count = DB::table('goods_v')->where('status', '=', 1)->count('*');
            if ($count >= 100) {
                $count = 100;
            }
        }
        if ($this->filter) {
            $hotGoods = DB::table('goods_v')
                ->where('status','=',1)
                ->whereDate('updated_at', '>=', $starTime)
                ->take($this->pageSize)
                ->orderBy('stars', 'desc')->get();
        } else {
            $hotGoods = DB::table('goods_v')
                ->where('status','=',1)
                ->take($this->pageSize)
                ->orderBy('stars', 'desc')->get();
        }

        $data = array(
            'activeIndex' => '3',
            'starFullVisible' => $navVisible['starFullVisible'],
            'cartFullVisible' => $navVisible['cartFullVisible'],
            'orderFullVisible' => $navVisible['orderFullVisible'],
            'hotGoods' => $hotGoods,
            'count' => $count,
        );
        return view('show.hot', compact('data'));
    }


    //加载新一页数据
    public function newPage($page)
    {
        $start = ($page - 1) * $this->pageSize;
        $starTime = Carbon::now()->subDays(30);

        if ($this->filter) {
            $newGoods = DB::table('goods_v')
                ->where('status','=',1)
                ->whereDate('updated_at', '>=', $starTime)
                ->skip($start)->take($this->pageSize)
                ->orderBy('stars', 'desc')->get();
        } else {
            $newGoods = DB::table('goods_v')
                ->where('status','=',1)
                ->skip($start)->take($this->pageSize)
                ->orderBy('stars', 'desc')->get();
        }
        return $this->withData($newGoods);
    }
}
